var self = this;
var host = window.location.protocol;
var URLBASE = host +'//'+ window.location.host;

function init () {
	this.getConstellations()
}

this.getConstellations = function() {
	console.log('[ConstellationsModel] getConstellations()')
	try {
		$.ajax({
			type: "GET",
			url:URLBASE+'/admin_constellations/',
			contentType: 'application/json',
			dataType: 'json'
		}).error(function(e) { 
			console.log("[ConstellationsModel] init error", e)
		}).done(function (data) {
			console.log("[ConstellationsModel] Constellations loaded", data.length)
			self.dataReceived(data)
			// self.initConstellations(data)

		});
	} catch(e) {
		console.log("[ConstellationsModel] getNextGame error", e)
	}
}

this.dataReceived = function(data) {
	console.log("[Main] constellation data received", data)
	for (var i = 0; i < data.length; i++) {
		var t1 = $('<h3>').html("username: " + data[i].username)
		var t2 = $('<h3>').html("constellation name: " + data[i].name)
		var img = $('<img>').attr('src', data[i].image_url)
	    $("#data").append(t1);
	    $("#data").append(t2);
	    $("#data").append(img);
	    $("#data").append(img);
	    var a =  $('<button>')
	    a.html('Delete item')

	    a.data('id', data[i].id)
	    a.click(function(evt) {
	    	console.log($(evt.target).data('id'))
	    	var checkstr =  confirm('are you sure you want to delete this?');
	    	if(checkstr == true){
	    	  self.deleteConstellation($(evt.target).data('id'))
	    	}else{
	    		console.log('delete canceled')
	    		return false;
	    	}
	    	
	    })
	    $("#data").append($('<br>'));	
	    $("#data").append(a);
	    $("#data").append($('<hr>'));	
	};
}

this.deleteConstellation = function(id) {
	console.log('[deleteConstellation] deleteConstellation()')
	
	try {
		$.ajax({
			type: "DELETE",
			url:URLBASE+'/delete_constellation/'+id,
		}).error(function(e) { 
			console.log("[deleteConstellation] init error", e)
		}).done(function (data) {
			location.reload(true)
			console.log("[deleteConstellation] Constellations loaded", data)

		});
	} catch(e) {
		console.log("[deleteConstellation] error", e)
	}
}

$(window).ready(function() {
    init();
    // shareView.init()
});
